import Vue from 'vue'

let loadingInstance = null

const createInstance = (text) => {
  const instance = new Vue({
    render(h) {
      let contentNode = [
        h('div', { attrs: { class: 'k-loading-mask' } }),
        h('div', { attrs: { class: 'k-loading-inner' } },
          [
            h('span', { attrs: { class: 'k-loading-icon' } }),
            text ? h('span', { attrs: { class: 'k-loading-text' } }, text) : null
          ])
      ]
      return h('div', { attrs: { class: 'k-loading' } }, [contentNode]);
    },
    methods: {
      destroy() {
        document.body.removeChild(this.$el)
        loadingInstance = null
      }
    }
  })
  const component = instance.$mount()
  document.body.appendChild(component.$el)
  return {
    destroy() {
      component.destroy()
    }
  }
}

let getLoading = (text) => {
  loadingInstance = loadingInstance || createInstance(text)
  return loadingInstance
}
let Loading = {}
Loading.show = (text) => {
  return getLoading(text)
}
Loading.hide = e => {
  if (loadingInstance) loadingInstance.destroy()
}

export default Loading